package com.woniu.day8.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.day8.pojo.House;
import com.woniu.day8.pojo.dto.HouseDto;
import com.woniu.day8.service.HouseService;
import com.woniu.day8.util.ResultMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/house")
@CrossOrigin
public class HouseController {

    @Autowired
    private HouseService houseService;

    /**
     * 查询房屋列表（分页+条件查询）
     */
    @PostMapping("/selectHouses")
    public ResultMessage selectHouses(@RequestBody HouseDto houseDto) {
        Long pageNum = houseDto.getPageNum();
        Long pageSize = houseDto.getPageSize();

        Page<House> page = new Page<>(pageNum, pageSize);
        House house = new House();
        BeanUtils.copyProperties(houseDto, house);

        Page<House> housePage = houseService.getHousePage(page, house);

        Map<String, Object> result = new HashMap<>();
        result.put("records", housePage.getRecords());
        result.put("total", housePage.getTotal());
        result.put("current", housePage.getCurrent());
        result.put("pages", housePage.getPages());
        result.put("size", housePage.getSize());

        return ResultMessage.success(result);
    }

    /**
     * 新增房屋
     */
    @PostMapping("/insertHouse")
    public ResultMessage insertHouse(@RequestBody House house) {
        boolean result = houseService.save(house);
        if (result) {
            return ResultMessage.success("新增成功");
        }
        return ResultMessage.fail("新增失败");
    }

    /**
     * 修改房屋
     */
    @PostMapping("/updateHouse")
    public ResultMessage updateHouse(@RequestBody House house) {
        boolean result = houseService.updateById(house);
        if (result) {
            return ResultMessage.success("修改成功");
        }
        return ResultMessage.fail("修改失败");
    }

    /**
     * 删除房屋
     */
    @PostMapping("/deleteHouse")
    public ResultMessage deleteHouse(@RequestBody House house) {
        boolean result = houseService.removeById(house.getId());
        if (result) {
            return ResultMessage.success("删除成功");
        }
        return ResultMessage.fail("删除失败");
    }
}
